﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Dao;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.Utils.GuoMi;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.LogTool;
using CastingWellEquipmentGUI.ViewModel.Common.ShowWindow;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace CastingWellEquipmentGUI.ViewModel
{
    public class LoginViewModel : ViewModelBase
    {

        private Visibility _LoginPanelVisibility;

        public Visibility LoginPanelVisibility
        {
            get { return _LoginPanelVisibility; }
            set
            {
                _LoginPanelVisibility = value;
                RaisePropertyChanged("LoginPanelVisibility");
            }
        }

        private Visibility _GifMediaLoginVisibility;

        public Visibility GifMediaLoginVisibility
        {
            get { return _GifMediaLoginVisibility; }
            set
            {
                _GifMediaLoginVisibility = value;
                RaisePropertyChanged("GifMediaLoginVisibility");
            }
        }

        #region 命令声明
        /// <summary>
        /// 退出程序命令
        /// </summary>
        public DelegateCommand CloseAppCommand { get; set; }
        /// <summary>
        /// 登陆命令
        /// </summary>
        public DelegateCommand LoginCommand { get; set; }
        /// <summary>
        /// 显示窗体命令
        /// </summary>
        public DelegateCommand ShowWindowCommand { get; set; }
        #endregion 命令声明
        #region 当前登录用户信息
        private User _LoginUser = new User();
        /// <summary>
        /// 登录用户
        /// </summary>
        public User LoginUser
        {
            get { return _LoginUser; }
            set
            {
                _LoginUser = value;
                RaisePropertyChanged("LoginUser");
            }

        }
        private User DataBaseUser = null;
        #endregion 当前登录用户信息
        /// <summary>
        /// 默认构造
        /// </summary>
        public LoginViewModel()
        {
            LoginPanelVisibility = Visibility.Visible;
            //调用初始化命令方法
            InitCommand();
        }
        #region 初始化命令以及命令处理器
        /// <summary>
        /// 初始化命令
        /// </summary>
        private void InitCommand()
        {

            CloseAppCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(CloseAppHandler)
            };
            LoginCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(LoginHandler)
            };
            ShowWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ShowWindowHandler)
            };

            GifMediaLoginVisibility = Visibility.Hidden;
            Messenger.Default.Register<string>(this, "GoLogin", (message) =>
            {


                //加载权限信息
                LoadUserPermissions(ref DataBaseUser);

                //执行登录逻辑
                LogTool.CurrentUser = DataBaseUser;
                //发送权限分析
                Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "Analysis form control structure generation permission"));
                LogTool.SaveLog("登录", "用户【" + DataBaseUser.UserName + "】登录了系统。");
                WindowManager.Show("Main", null);
                Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideLogin"));
            });
            LoginUser = new User();
            LoginUser.Account = "Admin";
            LoginUser.Password = "123456";
        }
        /// <summary>
        /// 退出程序命令处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void CloseAppHandler(object obj)
        {
            Environment.Exit(0);
        }
        /// <summary>
        /// 登录命令处理程序
        /// </summary>
        /// <param name="obj"></param>
        private void LoginHandler(object obj)
        {
            try
            {
                if (!KafkaHelper.InitConsumerByTagValueChanged())
                {
                    MessageBox.Show("连接网关服务器失败，请配置数据库IP地址或检查网络状况！");
                    return;
                }
                if (!KafkaHelper.InItProduce())
                {
                    MessageBox.Show("连接网关服务器失败，请配置数据库IP地址或检查网络状况！");
                    return;
                }
                if (!KafkaHelper.InitConsumerByTagChangeValue())
                {
                    MessageBox.Show("连接网关服务器失败，请配置数据库IP地址或检查网络状况！");
                    return;
                }
                if (!KafkaHelper.InitConsumerByAlarm())
                {
                    MessageBox.Show("连接网关服务器失败，请配置数据库IP地址或检查网络状况！");
                    return;
                }
                //if (!SocketHelper.InitSocket())
                //{
                //    MessageBox.Show("连接网关服务器失败，请配置数据库IP地址或检查网络状况！");
                //    return;
                //}
                if (!XyhUtils.PingIp(SystemConfig.dataBaseIpAddress))
                {
                    MessageBox.Show("无法连接到数据库服务器，无法登录，请配置数据库IP地址或检查网络状况！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                Sm4Crypto sm4 = new Sm4Crypto();
                if (LoginUser.Account == null || LoginUser.Account.Trim().Length == 0)
                {
                    MessageBox.Show("请输入账号！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                else if (LoginUser.Password == null || LoginUser.Password.Trim().Length == 0)
                {
                    MessageBox.Show("请输入密码！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                else if (XyhUtils.IsHasSQLInject(LoginUser.Account))
                {
                    MessageBox.Show("账号不可用包含SQL注入关键词！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                else if (XyhUtils.IsHasSQLInject(sm4.Encrypt_ECB_Str(LoginUser.Password)))
                {
                    MessageBox.Show("密码不可用包含SQL注入关键词！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                else
                {
                    User VerificationUser = new User
                    {
                        Account = LoginUser.Account,
                        Password = sm4.Encrypt_ECB_Str(LoginUser.Password)
                    };
                    string sql = "select * from [User] where Account = @Account and Password = @Password";
                    DataBaseUser = DapperToolsThisSystem.Query<User>(sql, VerificationUser);
                    if (DataBaseUser == null)
                    {
                        MessageBox.Show("账号或密码不正确!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    else
                    {
                        LoginPanelVisibility = Visibility.Hidden;
                        GifMediaLoginVisibility = Visibility.Visible;
                        Messenger.Default.Send(new NotificationMessage(this, "DoLogin"));
                    }
                }
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "登录异常");
            }
        }
        /// <summary>
        /// 打开窗体
        /// </summary>
        /// <param name="obj"></param>
        private void ShowWindowHandler(object obj)
        {
            ShowWindow.Show(obj.ToString());
        }

        /// <summary>
        /// 加载权限信息
        /// </summary>
        /// <param name="LoginUser"></param>
        private void LoadUserPermissions(ref User LoginUser)
        {
            string sql = "select * from Role where RoleId in ( select RoleId from UserAndRole where UserId = " + LoginUser.UserId + " )";
            ObservableCollection<Role> DataRole = DapperToolsThisSystem.QueryOc<Role>(sql);
            LoginUser.Roles = DataRole;
            for (int i = 0; i < LoginUser.Roles.Count; i++)
            {
                Role role = LoginUser.Roles[i];
                sql = @"SELECT 
                         a.PermissionsId,
                         a.PermissionsName,
                         a.FormId,
                         a.ControlId,
                         b.IsShow,
                         b.IsEnable
                        FROM
                        Permissions a
                        RIGHT JOIN PermissionsAndRole b ON a.PermissionsId = b.PermissionsId
                        WHERE B.RoleId = " + role.RoleId;
                ObservableCollection<Permissions> DataPermissions = DapperToolsThisSystem.QueryOc<Permissions>(sql);
                role.Permissions = DataPermissions;
                for (int j = 0; j < role.Permissions.Count; j++)
                {
                    Form WhereForm = new Form
                    {
                        FormId = role.Permissions[j].FormId
                    };
                    Form form = DapperToolsThisSystem.Query("select * from Form where FormId = @FormId", WhereForm);
                    if (form != null)
                    {
                        role.Permissions[j].PForm = form;
                        Control WhereControl = new Control
                        {
                            ControlId = role.Permissions[j].ControlId
                        };
                        string getControlSQL = @"select 
                                                a.ControlId,
                                                a.ControlName,
                                                a.ControlType,
                                                a.FormId,
                                                b.TagInfoId,
                                                b.RelationType,
                                                b.WarningType,
                                                b.StatusType,
                                                b.ContentId
                                             from Control a 
                                             left join ControlAndTagInfo b ON a.ControlId = b.ControlId
                                             where a.ControlId = @ControlId";
                        Control control = DapperToolsThisSystem.Query(getControlSQL, WhereControl);
                        if (control != null)
                        {
                            if (control.ControlName == "Button_ManualAutoMediation")
                            {
                                int u = 8;
                            }
                            role.Permissions[j].PControl = control;
                            TagInfo tagInfo = new TagInfo
                            {
                                Id = role.Permissions[j].PControl.TagInfoId
                            };
                            TagInfo tag = RedisHelper.GetHashKey<TagInfo>("Tag_Value", tagInfo.Id.ToString());
                            if (tag != null)
                            {
                                tagInfo.Value = RedisHelper.GetHashKey<TagInfo>("Tag_Value", tagInfo.Id.ToString()).Value;
                            }
                            else
                            {
                                tagInfo.Value = null;
                            }
                            role.Permissions[j].PControl.Tag = tagInfo;
                        }
                    }

                }

            }
        }
        #endregion 初始化命令以及命令处理器

    }
}
